﻿/*
 * master104.cpp
 *
 *  Created on: 2017年5月7日
 *      Author: work
 */

#include <iostream>
#include <boost/program_options.hpp>
#include <dm/os/protocol/protocolcontrolor.hpp>
#include <dm/os/protocol/protocollistenor.hpp>
#include <dm/os/ascom/tcplistner.hpp>
#include <dm/os/ascom/tcpclientdevice.hpp>
#include <dm/os/sys/task_agent.hpp>
#include <dm/os/msg/msgdriver.hpp>

#include "dm104master.h"

using namespace std;
using namespace boost::program_options;

using namespace dm::os;

int main( int argc,char* argv[] ){
	options_description desc("DM同步工具");
	desc.add_options()
			("help,h","显示本帮助信息")
			("version,v","显示版本及编译信息")
			("task_id",value<int>()->default_value(-1),"指定任务ID")
			("ip",value<string>(),"ip")
			("port",value<int>(),"端口")
			("device",value<string>(),"设备名.默认dm-sub")
			;

	variables_map vm;
	try{
		store(parse_command_line(argc,argv,desc),vm);
		notify(vm);
	}catch( std::exception& ex ){
		cout << ex.what()<<endl;
		return 1;
	}

	if( vm.count("version") ){
		cout <<"V1.0 构建于 "<<__DATE__<<endl;
		return 1;
	}

	if( vm.count("help") ){
		cout <<desc<<endl;
		return 1;
	}

	com::ios_t ios;

	com::CTcpClientAddr address;

	if( vm.count("ip") )
		address.setServerHost(vm["ip"].as<string>().c_str());
	else{
		cout <<"请指定主机IP"<<endl;
		return 0;
	}

	if( vm.count("port") )
		address.setServerPort( vm["port"].as<int>());
	else
		address.setServerPort(2404);

	dm::os::sys::CTaskAgent taskAgent( vm["task_id"].as<int>() );

	ascom::CTcpClientDevice* device = new ascom::CTcpClientDevice(ios);
	device->setAddress(address);

	protocol::CProtocolControlor* controlor = new protocol::CProtocolControlor(ios);
	CDm104Master* dm104master = new CDm104Master;

	if( vm.count("device") ){
		if( !dm104master->setDeviceByName(vm["device"].as<string>().c_str()) ){
			cout <<"系统内不存在设备:"<<vm["device"].as<string>()<<endl;
			return 0;
		}
	}else{
		if( !dm104master->setDeviceByName("dm-sub") ){
			cout <<"系统内不存在设备:dm-sub. 请用参数--device指定"<<endl;
			return 0;
		}
	}

	controlor->setProtocol(dm104master );
	controlor->setDevice(device);
	controlor->setAutoConnect();
	controlor->openDevice();

	com::CTimer timer(ios);
	timer.start_seconds(true,10);
	while( taskAgent.runOnce() ){
		ios.run_one();

		if( controlor->isExiting() )
			break;
	}

	return 0;
}


